﻿/** 自定义的按键相关函数的类,属于专门函数的合集,不可新建实例,所有函数作为类函数使用
  By setycyas @2023-01-31
*/

class MyKey {

  /* 可供外部调用的函数  
  */
  
  ;按键后放手,按住键的时间为duration
  press(key, duration := 50){
    send, {%key% down}
    sleep, %duration%
    send, {%key% up}
  }
  
  ;仅按下键
  keyDown(key){
    send, {%key% down}
  }
  ;仅放开键
  keyUp(key){
    send, {%key% up}
  }
  
  ;依次连续按下keys[]中的按键,按下时间间隔为数组delays[],按下最后一个键以后经过duration才一起放开所有按键
  ;注意delays的长度应该比keys小1
  pressKeys(keys, delays, duration := 50){
    local index, val
    for index, val in keys{
      send {%val% down}
      if (index < keys.Count())
        sleep, % delays[index]
    }
    sleep, %duration%
    for index, val in keys{
      send {%val% up}
    }
  }
  
  ;等待按键key放开,等待waitTime毫秒,每waitDuration毫秒检查一次,若发现按键放开返回+1,等待完毕未放开返回+0
  waitKeyUp(key, waitTime, waitDuration := 20){
    local temp1 := 0 ;计算总等待时间
    local delta := 0 ;下一次等待时间
    while (temp1 < waitTime) {
      delta := (waitTime-temp1 > waitDuration) ? (waitDuration) : (waitTime-temp1)
      if (!GetKeyState(key)) {
        return +1
      }
      sleep ,%delta%
      temp1 := temp1+delta
    }
    return +0
  }
  
  ;连续输入指令,相邻的两个key有重叠时间且最多同时有2个按键一起按下,等前一个key放开时,后面的key才会输入,keys和delays长度应该相同
  inputSkill(keys, delays){
    local i, v, curKey, curDelay, lastKey
    for i, v in keys {
      curKey := v
      curDelay := delays[i]
      if (i > 1)
        lastKey := keys[i-1]
      else
        lastKey := 0
      send {%curKey% down}
      sleep, %curDelay%
      if lastKey
        send {%lastKey% up}
      if (i = keys.Count())
        send {%curKey% up}
      sleep, 30 ;放开前一个按键与输入后一个按键之间需要有一点时间缓冲
    }
  }
  
  ;切换热键中断状态
  toggleHotkey(){
    Suspend, Toggle
  }
  
  ;连发,指定触发连发的按键为lunchKey,效果为连续按targetKey键,按键持续时间为duration,等待delay后再重新按
  ;当检测到lunchKey弹起时中止连发
  autoFire(lunchKey, targetKey, duration := 30, delay := 30){
    MyKey.press(targetKey, duration)
    while(!MyKey.waitKeyUp(lunchKey, delay)){
      MyKey.press(targetKey, duration)
    }
  }
  
}